﻿using System;
using System.Collections.Generic;
using System.Web.UI.HtmlControls;
using System.Data;
using System.Text;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;

public partial class Main_Inventory_DCOutwardEdit : System.Web.UI.Page
{
    string sql = "";
    string TFOID = "";
    string Vendor = "";

    string TAX = "";
    string CATEGORY = "";

    string FINYEAR = "";
    string TRNID = "";

    Datautility du = new Datautility();
    int dccounter = 0;
    List<string> listdccounter;
    List<string> listitem;
    List<string> listhidTITID;
    List<string> listhidTIDID;
    List<string> listuom;
    List<string> listhuomid;
    List<string> listqty;
    List<string> listbtnqty;
    List<string> listhidLocationBillLevel;
    List<string> listrate;
    List<string> listhidTaxRate;
    List<string> listamount;
    List<string> listhidtaxamt;
    protected override void LoadViewState(object savedState)
    {
        base.LoadViewState(savedState);
        overrideADDMORE();
    }
    protected void overrideADDMORE()
    {
        listdccounter = (List<string>)ViewState["listdccounter"];
        listitem = (List<string>)ViewState["listitem"];
        listhidTITID = (List<string>)ViewState["listhidTITID"];
        listhidTIDID = (List<string>)ViewState["listhidTIDID"];
        listuom = (List<string>)ViewState["listuom"];
        listhuomid = (List<string>)ViewState["listhuomid"];
        listqty = (List<string>)ViewState["listqty"];
        listbtnqty = (List<string>)ViewState["listbtnqty"];
        listhidLocationBillLevel = (List<string>)ViewState["listhidLocationBillLevel"];
        listrate = (List<string>)ViewState["listrate"];
        listhidTaxRate = (List<string>)ViewState["listhidTaxRate"];
        listamount = (List<string>)ViewState["listamount"];
        listhidtaxamt = (List<string>)ViewState["listhidtaxamt"];

        if (listdccounter != null)
        {
            int temdccounter = Convert.ToInt32(listdccounter.Count);
            for (int i = 0; i < temdccounter; i++)
            {
                dccounter++;

                HtmlTableRow row1 = new HtmlTableRow();

                HtmlTableCell cell1 = new HtmlTableCell();
                cell1.Align = "Center";
                DropDownList ddl = new DropDownList();
                ddl.ID = listitem[i].ToString();
                ddl.CssClass = "dropdown";
                ddl.Width = Unit.Percentage(95);
                binditem();
                //ddl.Attributes.Add("onchange", "return checkItemRepetion(this.id);");
                ddl.AutoPostBack = true;
                ddl.SelectedIndexChanged += new EventHandler(ddlitems_OnSelectedIndexChanged);

                HiddenField hidTITID = new HiddenField();
                hidTITID.ID = listhidTITID[i].ToString();

                HiddenField hidTIDID = new HiddenField();
                hidTIDID.ID = listhidTIDID[i].ToString();

                HtmlTableCell cell2 = new HtmlTableCell();
                cell2.Align = "Center";
                TextBox txtunit = new TextBox();
                txtunit.ID = listuom[i].ToString();
                txtunit.Width = Unit.Percentage(95);
               // txtunit.Attributes.Add("OnKeyDown", "return EnabledTabKey(this.ID,event);");
                txtunit.CssClass = "input";

                HiddenField huomid = new HiddenField();
                huomid.ID = listhuomid[i].ToString();

                HtmlTableCell cell3 = new HtmlTableCell();
                cell3.Align = "Center";
                TextBox txtquantity = new TextBox();
                txtquantity.ID = listqty[i].ToString();
                txtquantity.Width = Unit.Percentage(88);
                txtquantity.Attributes.Add("OnKeyDown", "return EnabledTabKey(this.ID,event);");
                txtquantity.CssClass = "inputnumber";

                Label lblspace = new Label();
                lblspace.Text = "&nbsp;";

                Button btnQtyBillLevel = new Button();
                btnQtyBillLevel.ID = listbtnqty[i].ToString();
                btnQtyBillLevel.CssClass = "button";
                btnQtyBillLevel.Width = Unit.Percentage(5);
                btnQtyBillLevel.Text = "...";

                HiddenField hidLocationBillLevel = new HiddenField();
                hidLocationBillLevel.ID = listhidLocationBillLevel[i].ToString();

                HtmlTableCell cell4 = new HtmlTableCell();
                cell4.Align = "Center";
                TextBox txtrate = new TextBox();
                txtrate.ID = listrate[i].ToString();
                txtrate.Width = Unit.Percentage(95);
             
                txtrate.Attributes.Add("onBlur", "return CalculateAmtQtyRate();");
                txtrate.CssClass = "inputnumber";

                HiddenField hidTaxRate = new HiddenField();
                hidTaxRate.ID = listhidTaxRate[i].ToString();

                HtmlTableCell cell5 = new HtmlTableCell();
                cell5.Align = "Center";
                TextBox txtamount = new TextBox();
                txtamount.ID = listamount[i].ToString();
                txtamount.Width = Unit.Percentage(95);
                txtamount.Attributes.Add("OnKeyDown", "return EnabledTabKey(this.ID,event);");
                txtamount.CssClass = "inputnumber";

                HiddenField hidtaxamt = new HiddenField();
                hidtaxamt.ID = listhidtaxamt[i].ToString();

                cell1.Controls.Add(ddl);
                cell1.Controls.Add(hidTITID);
                cell1.Controls.Add(hidTIDID);
                cell2.Controls.Add(txtunit);
                cell2.Controls.Add(huomid);
                cell3.Controls.Add(txtquantity);
                cell3.Controls.Add(lblspace);
                cell3.Controls.Add(btnQtyBillLevel);
                cell3.Controls.Add(hidLocationBillLevel);
                cell4.Controls.Add(txtrate);
                cell4.Controls.Add(hidTaxRate);
                cell5.Controls.Add(txtamount);
                cell5.Controls.Add(hidtaxamt);

                row1.Cells.Add(cell1);
                row1.Cells.Add(cell2);
                row1.Cells.Add(cell3);
                row1.Cells.Add(cell4);
                row1.Cells.Add(cell5);

                tblitem.Rows.Add(row1);
            }
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        MaintainScrollPositionOnPostBack = true;
        if (Request.QueryString["TFOID"] != null && Request.QueryString["TRNID"] != null)
        {
            TFOID = Request.QueryString["TFOID"].ToString();
            Vendor = Request.QueryString["Vendor"].ToString();
            TAX = Request.QueryString["TAX"].ToString();
            hidTRNID.Value = Request.QueryString["TRNID"].ToString();
            TRNID = Request.QueryString["TRNID"].ToString();
            CATEGORY = Request.QueryString["CATEGORY"].ToString();
            FINYEAR = Request.QueryString["FINYEAR"].ToString();
        }

        if (!IsPostBack)
        {
            listdccounter = new List<string>();
            ViewState["listdccounter"] = listdccounter;

            listitem = new List<string>();
            ViewState["listitem"] = listitem;

            listhidTITID = new List<string>();
            ViewState["listhidTITID"] = listhidTITID;

            listhidTIDID = new List<string>();
            ViewState["listhidTIDID"] = listhidTIDID;

            listuom = new List<string>();
            ViewState["listuom"] = listuom;

            listhuomid = new List<string>();
            ViewState["listhuomid"] = listhuomid;

            listqty = new List<string>();
            ViewState["listqty"] = listqty;

            listbtnqty = new List<string>();
            ViewState["listbtnqty"] = listbtnqty;

            listhidLocationBillLevel = new List<string>();
            ViewState["listhidLocationBillLevel"] = listhidLocationBillLevel;

            listrate = new List<string>();
            ViewState["listrate"] = listrate;

            listhidTaxRate = new List<string>();
            ViewState["listhidTaxRate"] = listhidTaxRate;

            listamount = new List<string>();
            ViewState["listamount"] = listamount;

            listhidtaxamt = new List<string>();
            ViewState["listhidtaxamt"] = listhidtaxamt;
            Bindddldcformat();
           
            bindtaxgroup();
            bindDeliveryAdd();
            BindCustomer();
            Bindcategory();
          
            BindMain();
           }
        
        BindJavaScriptBillLevel();
    }
    protected void BindCustomer()
    {
        DataTable dtCustomer = du.getdatausingprocedure("USP_ACC_GetLedgerForPurchaseInvoice");
        if (dtCustomer.Rows.Count > 0)
        {
            DdlCustomer.DataSource = dtCustomer;
            DdlCustomer.DataTextField = "LNAME";
            DdlCustomer.DataValueField = "LID";
            DdlCustomer.DataBind();
            DdlCustomer.Items.Insert(0, new ListItem("-Select Customer-", "0"));
        }
    }
    protected void Bindddldcformat()//Function for binding DCFormate Dropropdown
    {
        SqlParameter[] parr = {
                                  new SqlParameter("@TranType","2")
                              };
        DataTable dtformatname = du.getdatausingprocedure("USP_IVR_GetTransactionFormat", parr);
        if (dtformatname.Rows.Count > 0)
        {
            ddldcformat.DataSource = dtformatname;
            ddldcformat.DataTextField = "FormatName";
            ddldcformat.DataValueField = "Tfoid";
            ddldcformat.DataBind();
            ddldcformat.SelectedIndex = 0;
        }
    }
    protected void CheckTranFormat()
    {
        SqlParameter[] parrr = { new SqlParameter("@TFOID", TFOID) };
        DataTable dtpermission = du.getdatausingprocedure("CheckTranFormat", parrr);
        if (dtpermission.Rows.Count > 0)
        {
            if (dtpermission.Rows[0]["DELIVERYDETAILS"].ToString() == "False")
            {
                //divdeliverydetails.Disabled = true;
                txtmodeofdelivery.Enabled = false;
                txtfreightindicator.Enabled = false;
                txttransportername.Enabled = false;
                txtdocumentno.Enabled = false;
                txtdeliverydate.Enabled = false;
                txtvehicleno.Enabled = false;
                btnimage.Enabled = false;
                CalendarExtender1.Enabled = false;
                //spanRequireDate.Visible = false;
                //hidCheckDelivery.Value = "False";
            }
            else
            {
                //divdeliverydetails.Disabled = false;
                txtmodeofdelivery.Enabled = true;
                txtfreightindicator.Enabled = true;
                txttransportername.Enabled = true;
                txtdocumentno.Enabled = true;
                txtdeliverydate.Enabled = true;
                txtvehicleno.Enabled = true;
                btnimage.Enabled = true;
                CalendarExtender1.Enabled = true;
                //spanRequireDate.Visible = true;
                //hidCheckDelivery.Value = "True";
            }

            if (dtpermission.Rows[0]["PREPAREDBY"].ToString() == "True")
            {
                txtpreparedby.Enabled = true;
            }
            else
            {
                txtpreparedby.Enabled = false;
            }
            if (dtpermission.Rows[0]["CHECKEDBY"].ToString() == "True")
            {
                txtcheckedby.Enabled = true;
            }
            else
            {
                txtcheckedby.Enabled = false;
            }
            if (dtpermission.Rows[0]["AUTHSIGNATORY"].ToString() == "True")
            {
                txtauthorisedsignature.Enabled = true;
            }
            else
            {
                txtauthorisedsignature.Enabled = false;
            }
            if (dtpermission.Rows[0]["NOTE"].ToString() == "True")
            {
                txtnote.Enabled = true;
            }
            else
            {
                txtnote.Enabled = false;
            }
            if (dtpermission.Rows[0]["REMARKS"].ToString() == "True")
            {
                txtremarks.Enabled = true;
            }
            else
            {
                txtremarks.Enabled = false;
            }
        }

    }
    protected void DdlCustomer_SelectedIndexChanged(object sender, EventArgs e)
    {
        bindDeliveryAdd();
    }

    protected void bindDeliveryAdd() //Bind Delivery Address on the basis of dropdown selected value
    {

        SqlParameter[] parrr = { 
                                 new SqlParameter("@ledid",DdlCustomer.SelectedValue)
                               };
        DataTable dtdeladd = du.getdatausingprocedure("usp_get_deliveryadd_by_ledid", parrr);
        if (dtdeladd.Rows.Count > 0)
        {
            hidDeliveryId.Value = dtdeladd.Rows[0]["deliveryaddid"].ToString();
            StringBuilder sb = new StringBuilder();
            sb.Append(dtdeladd.Rows[0]["Title"].ToString() + " , ");
            sb.Append(dtdeladd.Rows[0]["contactname"].ToString() + "\n");
            sb.Append(dtdeladd.Rows[0]["add1"].ToString() + " ");
            sb.Append(dtdeladd.Rows[0]["add2"].ToString() + " ");
            sb.Append(dtdeladd.Rows[0]["add3"].ToString() + " ");
            sb.Append(dtdeladd.Rows[0]["pincode"].ToString() + "\n  ");
            sb.Append(dtdeladd.Rows[0]["state"].ToString() + "\n  ");
            sb.Append(dtdeladd.Rows[0]["country"].ToString() + " ");

            TxtDeliveryAddress.Text = sb.ToString();
        }
        else
        {
            TxtDeliveryAddress.Text = string.Empty;
        }
    }

    protected void bindtaxgroup()
    {
        SqlParameter[] parr = {
                                  new SqlParameter("@ISDCIN","0")
                              };
        DataTable dttaxgroup = du.getdatausingprocedure("USP_IVR_GetDCGroup", parr);
        if (dttaxgroup.Rows.Count > 0)
        {
            DdlTax.DataSource = dttaxgroup;
            DdlTax.DataTextField = "Subclass";
            DdlTax.DataValueField = "Id";
            DdlTax.DataBind();
            DdlTax.Items.Insert(0, new ListItem("-Tax Group-", "0"));
        }
    }

    private void EmptyTextBoxes(Control parent)
    {
        // Loop through all the controls on the page
        foreach (Control c in parent.Controls)
        {
            // Check and see if it's a textbox
            if ((c.GetType() == typeof(TextBox)))
            {
                // Since its a textbox clear out the text  
                ((TextBox)(c)).Text = "";
            }
            if ((c.GetType() == typeof(DropDownList)))
            {
                // Since its a textbox clear out the text  
                ((DropDownList)(c)).SelectedItem.Text = "";
            }
            // Now we need to call itself (recursive) because
            // all items (Panel, GroupBox, etc) is a container
            // so we need to check all containers for any
            // textboxes so we can clear them
            if (c.HasControls())
            {
                EmptyTextBoxes(c);
            }
        }
    }

    protected void Bindcategory()//Function for binding Category Dropropdown
    {
        DataTable dtcategory = du.getdatausingprocedure("USP_IVR_GetDCCategory");
        if (dtcategory.Rows.Count > 0)
        {
            DdlCategory.DataSource = dtcategory;
            DdlCategory.DataTextField = "CATEGORYNAME";
            DdlCategory.DataValueField = "CATEGORYCODE";
            DdlCategory.DataBind();
            DdlCategory.Items.Insert(0, new ListItem("-Select Category-", "0"));
        }
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("DCOutward.aspx?action=view");
    }

    protected void btnAddMore_Click(object sender, EventArgs e)
    {
        AddMoreRow();
        ViewState["prevcount"] = hcount.Value;
        binditem();
    }

    protected void AddMoreRow()
    {
        dccounter++;       
        listdccounter.Add(dccounter.ToString());
        HtmlTableRow row1 = new HtmlTableRow();
        HtmlTableCell cell1 = new HtmlTableCell();
        cell1.Align = "Center";
        DropDownList ddl = new DropDownList();
        ddl.ID = "ddlitems" + dccounter.ToString();
        ddl.CssClass = "dropdown";
        ddl.Width = Unit.Percentage(95);
        //ddl.Items.Add(new ListItem(ddl.ID, "1"));
        //ddl.Attributes.Add("onchange", "return checkItemRepetion(this.id);");
        ddl.AutoPostBack = true;
        ddl.SelectedIndexChanged += new EventHandler(ddlitems_OnSelectedIndexChanged);

        listitem.Add(ddl.ID);

        HiddenField hidTITID = new HiddenField();
        hidTITID.ID = "hidTITID" + dccounter.ToString();

        listhidTITID.Add(hidTITID.ID);

        HiddenField hidTIDID = new HiddenField();
        hidTIDID.ID = "hidTIDID" + dccounter.ToString();

        listhidTIDID.Add(hidTIDID.ID);

        HtmlTableCell cell2 = new HtmlTableCell();
        cell2.Align = "Center";
        TextBox txtunit = new TextBox();
        txtunit.ID = "txtunit" + dccounter.ToString();
        txtunit.Width = Unit.Percentage(95);
        //txtunit.Attributes.Add("OnKeyDown", "return EnabledTabKey(this.ID,event);");
        txtunit.CssClass = "input";
        listuom.Add(txtunit.ID);

        HiddenField huomid = new HiddenField();
        huomid.ID = "huomid" + dccounter.ToString();
        listhuomid.Add(huomid.ID);

        HtmlTableCell cell3 = new HtmlTableCell();
        cell3.Align = "Center";
        TextBox txtquantity = new TextBox();
        txtquantity.ID = "txtquantity" + dccounter.ToString();
        txtquantity.Width = Unit.Percentage(88);
        txtquantity.Attributes.Add("OnKeyDown", "return EnabledTabKey(this.ID,event);");
        txtquantity.CssClass = "inputnumber";
        listqty.Add(txtquantity.ID);

        Label lblspace = new Label();
        lblspace.Text = "&nbsp;";

        Button btnQtyBillLevel = new Button();
        btnQtyBillLevel.ID = "btnQtyBillLevel" + dccounter.ToString();
        btnQtyBillLevel.CssClass = "button";
        btnQtyBillLevel.Width = Unit.Percentage(5);
        btnQtyBillLevel.Text = "...";

        listbtnqty.Add(btnQtyBillLevel.ID);

        HiddenField hidLocationBillLevel = new HiddenField();
        hidLocationBillLevel.ID = "hidLocationBillLevel" + dccounter.ToString();
        listhidLocationBillLevel.Add(hidLocationBillLevel.ID);

        HtmlTableCell cell4 = new HtmlTableCell();
        cell4.Align = "Center";
        TextBox txtrate = new TextBox();
        txtrate.ID = "txtrate" + dccounter.ToString();
        txtrate.Width = Unit.Percentage(95);
        //txtrate.Attributes.Add("OnKeyPress", "return isNumberKey(this.ID,event);");
        txtrate.Attributes.Add("onBlur", "return CalculateAmtQtyRate();");
        txtrate.CssClass = "inputnumber";
        listrate.Add(txtrate.ID);

        HiddenField hidTaxRate = new HiddenField();
        hidTaxRate.ID = "hidTaxRate" + dccounter.ToString();
        listhidTaxRate.Add(hidTaxRate.ID);

        HtmlTableCell cell5 = new HtmlTableCell();
        cell5.Align = "Center";
        TextBox txtamount = new TextBox();
        txtamount.ID = "txtamount" + dccounter.ToString();
        txtamount.Width = Unit.Percentage(95);
        txtamount.Attributes.Add("OnKeyDown", "return EnabledTabKey(this.ID,event);");
        txtamount.CssClass = "inputnumber";
        listamount.Add(txtamount.ID);

        HiddenField hidtaxamt = new HiddenField();
        hidtaxamt.ID = "hidtaxamt" + dccounter.ToString();
        listhidtaxamt.Add(hidtaxamt.ID);

        cell1.Controls.Add(ddl);
        cell1.Controls.Add(hidTITID);
        cell1.Controls.Add(hidTIDID);
        cell2.Controls.Add(txtunit);
        cell2.Controls.Add(huomid);
        cell3.Controls.Add(txtquantity);
        cell3.Controls.Add(lblspace);
        cell3.Controls.Add(btnQtyBillLevel);
        cell3.Controls.Add(hidLocationBillLevel);
        cell4.Controls.Add(txtrate);
        cell4.Controls.Add(hidTaxRate);
        cell5.Controls.Add(txtamount);
        cell5.Controls.Add(hidtaxamt);

        row1.Cells.Add(cell1);
        row1.Cells.Add(cell2);
        row1.Cells.Add(cell3);
        row1.Cells.Add(cell4);
        row1.Cells.Add(cell5);

        tblitem.Rows.Add(row1);
        hcount.Value = dccounter.ToString();
       
        ViewState["listdccounter"] = listdccounter;
        ViewState["listitem"] = listitem;
        ViewState["listhidTITID"] = listhidTITID;
        ViewState["listhidTIDID"] = listhidTIDID;
        ViewState["listuom"] = listuom;
        ViewState["listqty"] = listqty;
        ViewState["listhuomid"] = listhuomid;
        ViewState["listbtnqty"] = listbtnqty;
        ViewState["listhidLocationBillLevel"] = listhidLocationBillLevel;
        ViewState["listrate"] = listrate;
        ViewState["listhidTaxRate"] = listhidTaxRate;
        ViewState["listamount"] = listamount;
        ViewState["listhidtaxamt"] = listhidtaxamt;

    }
    protected void binditem()
    {
        int start = 1;
        if (ViewState["prevcount"] != null)
        {
            start = Convert.ToInt16(ViewState["prevcount"].ToString());
        }
        int count = Convert.ToInt32(hcount.Value);
        
        for (int i = start; i <= count; i++)
        {   
            DropDownList ddl = (DropDownList)tblitem.FindControl("ddlitems" + i.ToString());
            SqlParameter[] sparam ={
                                   new SqlParameter("@TFOID",ddldcformat.SelectedValue)
                               };
            DataTable dtitem = du.getdatausingprocedure("USP_IVR_GetItemForPurchaseInvoice", sparam);
            if (dtitem.Rows.Count > 0)
            {
                ddl.DataSource = dtitem;
                ddl.DataTextField = "ITMNAME";
                ddl.DataValueField = "ITMID";
                ddl.DataBind();
                ddl.Items.Insert(0, new ListItem("-Select Items-", "0"));
            }
        }
    }

    protected void ddlitems_OnSelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList ddl = (DropDownList)sender;
        string ddlid = ddl.ID.ToString().Substring(8);
        int rowno = Convert.ToInt32(ddlid.ToString());
        TextBox txtunit = (TextBox)tblitem.Rows[rowno].FindControl("txtunit" + rowno.ToString());
        HiddenField huono = (HiddenField)tblitem.Rows[rowno].FindControl("huomid" + rowno.ToString());
        txtunit.Text = string.Empty;
        huono.Value = string.Empty;
       

        SqlParameter[] parr = { 
                              new SqlParameter("@itemid",ddl.SelectedValue)
                              };
        DataTable dt = du.getdatausingprocedure("usp_ivr_get_uom_by_itemid", parr);
        if (dt.Rows.Count > 0)
        {
            txtunit.Text = dt.Rows[0]["UOMNAME"].ToString();
            huono.Value = dt.Rows[0]["UOMID"].ToString();
        }
         BindJavaScriptBillLevel();
    }

    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        InsertItemTranMainBillLevel();
    }

    //
    protected string EditBindLocation(string ITMID, string TITID)
    {
        string LocationIdandQty = string.Empty;
        if (ITMID != string.Empty && TITID != string.Empty)
        {
            SqlParameter[] parma = {
                                    new SqlParameter("@TITID",TITID)
                                   };
            DataTable dtDetaillocation = du.getdatausingprocedure("usp_get_DCIn_Edit_ItemsDetails", parma);
            if (dtDetaillocation.Rows.Count > 0)
            {
                for (int i = 0; i < dtDetaillocation.Rows.Count; i++)
                {
                    if (isBatchEnabled(ITMID) && isWarrantyEnabled(ITMID))
                    {
                        if (i == 0)
                        {
                            LocationIdandQty += dtDetaillocation.Rows[i]["whsid"].ToString() + ',' + string.Format("{0:0.00}", dtDetaillocation.Rows[i]["DETQTY"].ToString()) + '|' + dtDetaillocation.Rows[i]["BATID"].ToString() + ':' + dtDetaillocation.Rows[i]["WARRANTY"].ToString() + ';' + dtDetaillocation.Rows[i]["WARRANTYPERIOD"].ToString();
                        }
                        else if (i > 0)
                        {
                            LocationIdandQty += "/" + dtDetaillocation.Rows[i]["whsid"].ToString() + ',' + string.Format("{0:0.00}", dtDetaillocation.Rows[i]["DETQTY"].ToString()) + '|' + dtDetaillocation.Rows[i]["BATID"].ToString() + ':' + dtDetaillocation.Rows[i]["WARRANTY"].ToString() + ';' + dtDetaillocation.Rows[i]["WARRANTYPERIOD"].ToString();
                        }
                    }
                    else if (isBatchEnabled(ITMID) && !isWarrantyEnabled(ITMID))
                    {
                        if (i == 0)
                        {
                            LocationIdandQty += dtDetaillocation.Rows[i]["whsid"].ToString() + ',' + string.Format("{0:0.00}", dtDetaillocation.Rows[i]["DETQTY"].ToString()) + '|' + dtDetaillocation.Rows[i]["BATID"].ToString();
                        }
                        else if (i > 0)
                        {
                            LocationIdandQty += "/" + dtDetaillocation.Rows[i]["whsid"].ToString() + ',' + string.Format("{0:0.00}", dtDetaillocation.Rows[i]["DETQTY"].ToString()) + '|' + dtDetaillocation.Rows[i]["BATID"].ToString();
                        }
                    }
                    else if (!isBatchEnabled(ITMID) && !isWarrantyEnabled(ITMID))
                    {
                        if (i == 0)
                        {
                            LocationIdandQty += dtDetaillocation.Rows[i]["whsid"].ToString() + ',' + string.Format("{0:0.00}", dtDetaillocation.Rows[i]["DETQTY"].ToString());
                        }
                        else if (i > 0)
                        {
                            LocationIdandQty += "/" + dtDetaillocation.Rows[i]["whsid"].ToString() + ',' + string.Format("{0:0.00}", dtDetaillocation.Rows[i]["DETQTY"].ToString());
                        }
                    }
                }
            }
        }
        return LocationIdandQty;
    }
    protected string EditDetailedLocation(string TITID)
    {
        string Detailid = string.Empty;
        if (TITID != string.Empty)
        {
            SqlParameter[] parma = {
                                    new SqlParameter("@TITID",TITID)
                                   };
            DataTable dtDetaillocation = du.getdatausingprocedure("usp_get_DCIn_Edit_ItemsDetails", parma);
            if (dtDetaillocation.Rows.Count > 0)
            {
                for (int i = 0; i < dtDetaillocation.Rows.Count; i++)
                {
                    if (i == 0)
                    {
                        Detailid += dtDetaillocation.Rows[i]["TIDID"].ToString();
                    }
                    else if (i > 0)
                    {
                        Detailid += "/" + dtDetaillocation.Rows[i]["TIDID"].ToString();
                    }
                }
            }
        }
        return Detailid;
    }
    protected bool isBatchEnabled(string ItemId)//A common function for check item batch enabled or not
    {
        bool Flag = true;
        if (ItemId.ToString() != string.Empty)
        {
            sql = "Select ITMBATCH from IVR_ITEM Where ITMID='" + ItemId.ToString() + "'";
            DataTable DT = du.getdata(sql);
            if (DT.Rows.Count > 0)
            {
                if (Convert.ToDouble(DT.Rows[0]["ITMBATCH"]) > 0)
                {
                    Flag = true;
                }
                else
                {
                    Flag = false;
                }
            }
        }
        return Flag;
    }
    protected bool isWarrantyEnabled(string ItemId)//A common function for check item warranty enabled or not
    {
        bool Flag = true;
        if (ItemId.ToString() != string.Empty)
        {
            sql = "Select ITMBATCH, ITMBATCHOPT from IVR_ITEM Where ITMID='" + ItemId.ToString() + "'";
            DataTable DT = du.getdata(sql);
            if (DT.Rows.Count > 0)
            {
                if (Convert.ToDouble(DT.Rows[0]["ITMBATCH"]) > 0 && Convert.ToDouble(DT.Rows[0]["ITMBATCHOPT"]) == 1)
                {
                    Flag = true;
                }
                else
                {
                    Flag = false;
                }
            }
        }
        return Flag;
    }

    //

    protected void BindMain()
    {
        ddldcformat.SelectedValue = TFOID;
        CheckTranFormat();
        //ddldcformat_SelectedIndexChanged(this, EventArgs.Empty);
        SqlParameter[] parm = {
                                  new SqlParameter("@trnid", TRNID)
                              };
        DataTable dtmain = du.getdatausingprocedure("usp_ivr_DCoutward_Insert_TRNID", parm);
        //lblMsg.Text = dtmain.Rows.Count.ToString();
        if (dtmain.Rows.Count > 0)
        {
          
            //lblMsg.Text = dtmain.Rows[0]["TRNDATE"].ToString();
            txtdate.Text = string.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(dtmain.Rows[0]["TRNDATE"].ToString())).Replace("01/01/1900", "");
            DdlCategory.SelectedValue = CATEGORY;
            DdlCustomer.SelectedValue = Vendor;
            DdlTax.SelectedValue = dtmain.Rows[0]["DCTAX_SUBCLASSID"].ToString();
            txtVoucher.Text = dtmain.Rows[0]["TRNNUM"].ToString();
            hidDeliveryId.Value = dtmain.Rows[0]["SHIPTO_VSTID"].ToString();
            if (dtmain.Rows[0]["SHIPTO_VSTID"].ToString() != string.Empty)
            {
                SqlParameter[] parm1 = {
                                          new SqlParameter("@Deliveryaddid",dtmain.Rows[0]["SHIPTO_VSTID"].ToString())
                                      };
                DataTable dt1 = du.getdatausingprocedure("usp_ivr_BindDeliveryadd_by_id", parm1);
                if (dt1.Rows.Count > 0)
                {
                    StringBuilder sb = new StringBuilder();
                    sb.Append(dt1.Rows[0]["Title"].ToString() + " , ");
                    sb.Append(dt1.Rows[0]["contactname"].ToString() + "\n");
                    sb.Append(dt1.Rows[0]["address"].ToString() + " ");
                    sb.Append(dt1.Rows[0]["pincode"].ToString() + "\n  ");
                    //sb.Append(dt1.Rows[0]["state"].ToString() + "\n  ");
                    sb.Append(dt1.Rows[0]["country"].ToString() + " ");
                    TxtDeliveryAddress.Text = sb.ToString();
                }
            }
            if (dtmain.Rows[0]["TRNID"].ToString() != string.Empty)
            {
                SqlParameter[] parm2 = { 
                                           new SqlParameter("@TRNID", dtmain.Rows[0]["TRNID"].ToString())
                                       };
                DataTable dtdtails = du.getdatausingprocedure("usp_ivr_BindDeliveryDetails_by_id", parm2);
                if (dtdtails.Rows.Count > 0)
                {
                    txtmodeofdelivery.Text = dtdtails.Rows[0]["MODEOFDELIVERY"].ToString();
                    txtfreightindicator.Text = dtdtails.Rows[0]["FREIGHTINDICATOR"].ToString();
                    txttransportername.Text = dtdtails.Rows[0]["TRANSPORTNAME"].ToString();
                    txtdocumentno.Text = dtdtails.Rows[0]["DOCUMENTNUM"].ToString();
                    txtdeliverydate.Text = string.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(dtdtails.Rows[0]["DELIVERYDATE"].ToString())).Replace("01/01/1900", "");
                    txtvehicleno.Text = dtdtails.Rows[0]["VEHICLENUM"].ToString();
                }
            }
            if (dtmain.Rows[0]["TRNID"].ToString() != string.Empty)
            {
                SqlParameter[] parm3 = {
                                           new SqlParameter("@TRNID", dtmain.Rows[0]["TRNID"].ToString())
                                       };
                DataTable dtother = du.getdatausingprocedure("usp_ivr_BindotherDetails_by_id", parm3);
                if (dtother.Rows.Count > 0)
                {
                    txtpreparedby.Text = dtother.Rows[0]["PREPAREDBY"].ToString();
                    txtcheckedby.Text = dtother.Rows[0]["CHECKEDBY"].ToString();
                    txtauthorisedsignature.Text = dtother.Rows[0]["AUTHRSDSIGNAT"].ToString();
                    txtnote.Text = dtother.Rows[0]["NOTE"].ToString();
                    txtremarks.Text = dtother.Rows[0]["REMARKS"].ToString();
                }
            }
            if (dtmain.Rows[0]["TRNID"].ToString() != string.Empty)
            {
                SqlParameter[] parm4 = {
                                          new SqlParameter("@TRNID", dtmain.Rows[0]["TRNID"].ToString())
                                       };
                DataTable dtitems = du.getdatausingprocedure("usp_Ivr_Bindtranitem_by_id", parm4);
                if (dtitems.Rows.Count > 0)
                {
                    for (int i = 1; i <= dtitems.Rows.Count; i++)
                    {
                        AddMoreRow();
                        BindJavaScriptBillLevel();
                    }
                    EditBindItems(dtitems);
                    binditem();

                   
                }
            }
        }
    }
    protected void EditBindItems(DataTable dtitems)
    {
        if (dtitems.Rows.Count > 0)
        {
            for (int i = 1; i <= dtitems.Rows.Count; i++)
            {
                DropDownList ddlItemBillLevel = (DropDownList)tblitem.Rows[i].FindControl("ddlitems" + i.ToString());
                
                HiddenField hidTITID = (HiddenField)tblitem.Rows[i].FindControl("hidTITID" + i.ToString());
                HiddenField hidunitIdBillLevel = (HiddenField)tblitem.Rows[i].FindControl("huomid" + i.ToString());
                TextBox txtunit = (TextBox)tblitem.Rows[i].FindControl("txtunit" + i.ToString());
                TextBox txtQuantityBillLevel = (TextBox)tblitem.Rows[i].FindControl("txtquantity" + i.ToString());
                TextBox txtRateBillLevel = (TextBox)tblitem.Rows[i].FindControl("txtrate" + i.ToString());
                TextBox txtAmountBillLevel = (TextBox)tblitem.Rows[i].FindControl("txtamount" + i.ToString());
                HiddenField hidLocationBillLevel = (HiddenField)tblitem.Rows[i].FindControl("hidLocationBillLevel" + i.ToString());
                HiddenField hidTIDID = (HiddenField)tblitem.Rows[i].FindControl("hidTIDID" + i.ToString());

                ddlItemBillLevel.SelectedValue = dtitems.Rows[i - 1]["ITMID"].ToString();
                ddlitems_OnSelectedIndexChanged(ddlItemBillLevel, EventArgs.Empty);
                hidunitIdBillLevel.Value = dtitems.Rows[i - 1]["UOMID"].ToString();
                txtQuantityBillLevel.Text = dtitems.Rows[i - 1]["ITMQTY"].ToString();
                txtRateBillLevel.Text = dtitems.Rows[i - 1]["RATE"].ToString();
                txtAmountBillLevel.Text = dtitems.Rows[i - 1]["ITMAMT"].ToString();
                hidLocationBillLevel.Value = EditBindLocation(dtitems.Rows[i - 1]["ITMID"].ToString(), dtitems.Rows[i - 1]["TITID"].ToString());

                SqlParameter[] parm = { new SqlParameter("@itemid", dtitems.Rows[i - 1]["ITMID"].ToString()) };
                DataTable dtuom = du.getdatausingprocedure("usp_ivr_get_uom_by_itemid", parm);
                
                if (dtuom.Rows.Count > 0)
                {
                    txtunit.Text = dtuom.Rows[0]["UOMNAME"].ToString();
                }
            }
        }
    }

    protected void ddldcformat_SelectedIndexChanged1(object sender, EventArgs e)
    {
        lblMsg.Text = "";
        int finyear = 0;
        if (Session["FINYEAR"] != null)
        {
            finyear = Convert.ToInt32(FINYEAR); // Come from inward for edit
        }
        else
        {
            Response.Redirect("~/SessionExpired.aspx");
        }
        SqlParameter[] parma = {
                                  new SqlParameter("@TRNID",TRNID)
                                 };
        DataTable dtdcformatno = du.getdatausingprocedure("usp_ivr_Get_DCNO_by_TRNID", parma);
        if (dtdcformatno.Rows.Count > 0)
        {
            txtPrefix.Enabled = false;
            txtVoucher.Enabled = false;
            txtSuffix.Enabled = false;

            txtPrefix.Text = dtdcformatno.Rows[0]["NUMPREFIX"].ToString();
            txtVoucher.Text = dtdcformatno.Rows[0]["trnnum"].ToString();
            txtSuffix.Text = dtdcformatno.Rows[0]["NUMSUFFIX"].ToString();
        }

    }

    protected void BindJavaScriptBillLevel()//A common function for add javascript attribute to btn quantity
    {
        int intCount = Convert.ToInt32(hcount.Value);
        for (int i = 1; i <= intCount; i++)
        {
            DropDownList ddlitems = (DropDownList)tblitem.Rows[i].FindControl("ddlitems" + i.ToString());
            TextBox txtquantity = (TextBox)tblitem.Rows[i].FindControl("txtquantity" + i.ToString());
            HiddenField hidLocationBillLevel = (HiddenField)tblitem.Rows[i].FindControl("hidLocationBillLevel" + i.ToString());
            Button btnQtyBillLevel = (Button)tblitem.Rows[i].FindControl("btnQtyBillLevel" + i.ToString());
            btnQtyBillLevel.Attributes.Add("onclick", "return GetQuantity('" + ddlitems.SelectedValue + "', '" + txtquantity.ClientID.ToString() + "', '" + hidLocationBillLevel.ClientID.ToString() + "');");
        }
    }
    //
    protected void InsertItemTranMainBillLevel()
    {
        string strFinYear = string.Empty;
        string strTransDate = string.Empty;
        string strEffectiveDate = string.Format("{0:MM/dd/yyyy}", System.DateTime.Now).ToString();
        sql = "Select * from MAS_FINYEAR";
        DataTable DTFinYear = du.getdata(sql);
        if (DTFinYear.Rows.Count > 0)
        {
            strFinYear = DTFinYear.Rows[0]["FINYEAR"].ToString();
        }
        if (txtdate.Text.ToString() != string.Empty)
        {
            string[] str = txtdate.Text.ToString().Split('/');
            strTransDate = str[1].ToString() + "/" + str[0].ToString() + "/" + str[2].ToString();
        }


        SqlParameter[] sparam ={
                                   new SqlParameter("@TRNID",hidTRNID.Value),
                                    new SqlParameter("@TRANTYPEID","2"),
                                    new SqlParameter("@FINYEAR", strFinYear.ToString()),
                                    new SqlParameter("@TFOID", ddldcformat.SelectedValue),
                                    new SqlParameter("@TRNNUM", txtVoucher.Text.Trim()),
                                    new SqlParameter("@TRNDATE",strTransDate),
                                    new SqlParameter("@VENDCUST_LID",DdlCustomer.SelectedValue ),
                                    new SqlParameter("@TAX_MAINCLASSID", "0"),
                                    new SqlParameter("@TRNSTATUS","1"),
                                    new SqlParameter("@SHIPTO_VSTID", hidDeliveryId.Value),
                                    new SqlParameter("@MODEOFPAY","0"),
                                    new SqlParameter("@CREDITPERIOD","0"),
                                    new SqlParameter("@DCTAX_SUBCLASSID",DdlTax.SelectedValue),
                                    new SqlParameter("@DC_CATEGORYCODE",DdlCategory.SelectedValue),
                                    new SqlParameter("@ENAME",Session["username"].ToString())      
                                        //
                               };
        int intResult = du.executeprocedure("USP_IVR_UpdateTranMain", sparam);
       
        InsertTranDelivery(hidTRNID.Value);
        InsertTranOthers(hidTRNID.Value);
        InsertItemTranItem(hidTRNID.Value);
        lblMsg.Attributes.Remove("class");
        lblMsg.Attributes.Add("class", "true");
        lblMsg.Text = "DC Outward Updated";
    }

   
    protected void InsertTranOthers(string tranId)
    {
        if (tranId.ToString() != string.Empty)
        {
            SqlParameter[] sparam =
                                    {
                                        new SqlParameter("@TRNID",tranId.ToString()),
                                        new SqlParameter("@PREPAREDBY",txtpreparedby.Text.Trim()),
                                        new SqlParameter("@CHECKEDBY",txtcheckedby.Text.Trim()),
                                        new SqlParameter("@AUTHRSDSIGNAT",txtauthorisedsignature.Text.Trim()),
                                        new SqlParameter("@NOTE",txtnote.Text.ToString()),
                                        new SqlParameter("@REMARKS",txtremarks.Text.Trim())                                        
                                    };
            du.executeprocedure("USP_IVR_SaveTranOthers", sparam);
        }
    }
    protected void InsertTranDelivery(string tranId)
    {
        if (tranId.ToString() != string.Empty)
        {
            string strDeliveryDate = "1/1/1900";
            if (txtdeliverydate.Text != string.Empty)
            {
                string[] str = txtdeliverydate.Text.ToString().Split('/');
                strDeliveryDate = str[1] + "/" + str[0] + "/" + str[2];
            }
            SqlParameter[] sparam =
                                    {
                                        new SqlParameter("@TRNID",tranId.ToString()),
                                        new SqlParameter("@MODEOFDELIVERY",txtmodeofdelivery.Text.Trim()),
                                        new SqlParameter("@DELIVERYDATE",strDeliveryDate) ,
                                        new SqlParameter("@DOCUMENTNUM",txtdocumentno.Text.Trim()),
                                        new SqlParameter("@VEHICLENUM",txtvehicleno.Text.Trim()),
                                        new SqlParameter("@FREIGHTINDICATOR",txtfreightindicator.Text.Trim()),
                                        new SqlParameter("@TRANSPORTNAME",txttransportername.Text.Trim())                                                                              
                                    };
            int re = du.executeprocedure("USP_IVR_SaveTranDelivery", sparam);

        }
    }
    protected void InsertItemTranItem(string tranId) 
    {
        if (tranId.ToString() != string.Empty)
        {
            int intResult = 0;
            int intCount = Convert.ToInt32(hcount.Value);
             SqlParameter[] parm = {
                                              new SqlParameter("@trnid", TRNID)
                                          };
                    du.executeprocedure("usp_deleteDcoutwarditem_by_trnid", parm); 
            for (int i = 1; i <= intCount; i++)
            {
                DropDownList ddlItem = (DropDownList)tblitem.Rows[i].FindControl("ddlitems" + i.ToString());
                  HiddenField hidTITID = (HiddenField)tblitem.Rows[i].FindControl("hidTITID" + i.ToString());
                HiddenField hidunitId = (HiddenField)tblitem.Rows[i].FindControl("huomid" + i.ToString());
                TextBox txtQuantity = (TextBox)tblitem.Rows[i].FindControl("txtquantity" + i.ToString());
                TextBox txtRate = (TextBox)tblitem.Rows[i].FindControl("txtrate" + i.ToString());
                TextBox txtAmount = (TextBox)tblitem.Rows[i].FindControl("txtamount" + i.ToString());
                if (txtQuantity.Text != string.Empty && txtRate.Text != string.Empty)
                {
                    double dblItemAmount = 0;
                    dblItemAmount = Convert.ToDouble(txtAmount.Text);
                    if (hidTITID.Value != string.Empty)
                    {
                        SqlParameter[] sparam ={
                                   new SqlParameter("@TRNID",TRNID),
                                   new SqlParameter("@ITMID",ddlItem.SelectedValue ),
                                   new SqlParameter("@ITMQTY",txtQuantity.Text.Trim()),
                                   new SqlParameter("@UOMID",hidunitId.Value.ToString()),
                                   new SqlParameter("@RATE",txtRate.Text.Trim()),
                                   new SqlParameter("@GROSSAMT",txtAmount.Text.Trim()),
                                   new SqlParameter("@NETAMT",dblItemAmount),
                                   new SqlParameter("@TAX_TXMASID","0"),
                                   new SqlParameter("@TAXPER","0"),
                                   new SqlParameter("@TAXAMT","0"),
                                   new SqlParameter("@ITMAMT",dblItemAmount),
                                   new SqlParameter("@ITMPENDINGQTY",txtQuantity.Text.Trim()),                               
                               };
                        intResult = du.executeprocedure("USP_IVR_UpdateTranItem", sparam);
                    }
                    else
                    {
                        SqlParameter[] sparam ={
                                   new SqlParameter("@TRNID",TRNID),
                                   new SqlParameter("@ITMID",ddlItem.SelectedValue ),
                                   new SqlParameter("@ITMQTY",txtQuantity.Text.Trim()),
                                   new SqlParameter("@UOMID",hidunitId.Value.ToString()),
                                   new SqlParameter("@RATE",txtRate.Text.Trim()),
                                   new SqlParameter("@GROSSAMT",txtAmount.Text.Trim()),
                                   new SqlParameter("@NETAMT",dblItemAmount),
                                   new SqlParameter("@TAX_TXMASID","0"),
                                   new SqlParameter("@TAXPER","0"),
                                   new SqlParameter("@TAXAMT","0"),
                                   new SqlParameter("@ITMAMT",dblItemAmount),
                                   new SqlParameter("@ITMPENDINGQTY",txtQuantity.Text.Trim()),                               
                               };
                        intResult = du.executeprocedure("USP_IVR_SaveTranItem", sparam);
                    }
                }
                if (intResult > 0)
                {
                    savemainItemDetails(tranId, hidTITID.Value, i);
                    intResult = 0;
                }
            }
        }
    }
    protected void savemainItemDetails(string tranId, string tranItemId, int rowId)
    {
        if (tranId.ToString() != string.Empty && tranItemId.ToString() != string.Empty)
        {
            string strsql = "";
            string strTransDate = string.Empty;
            if (txtdate.Text.ToString() != string.Empty)
            {
                string[] str = txtdate.Text.ToString().Split('/');
                strTransDate = str[1].ToString() + "/" + str[0].ToString() + "/" + str[2].ToString();
            }
            DropDownList ddlItems = (DropDownList)tblitem.Rows[rowId].FindControl("ddlitems" + rowId.ToString());
            TextBox txtQuantity = (TextBox)tblitem.Rows[rowId].FindControl("txtquantity" + rowId.ToString());
            TextBox txtRate = (TextBox)tblitem.Rows[rowId].FindControl("txtrate" + rowId.ToString());
            HiddenField hidLocation = (HiddenField)tblitem.Rows[rowId].FindControl("hidLocationBillLevel" + rowId.ToString());
            HiddenField hidTIDID = (HiddenField)tblitem.Rows[rowId].FindControl("hidTIDID" + rowId.ToString());

            if (txtQuantity.Text != string.Empty && txtRate.Text != string.Empty)
            {
                if (hidLocation.Value.ToString() != string.Empty)
                {
                    if (isBatchEnabled(ddlItems.SelectedValue) && isWarrantyEnabled(ddlItems.SelectedValue))
                    {
                        List<string> lstLocationId = new List<string>();
                        List<string> lstBatchId = new List<string>();
                        List<string> lstLocationQty = new List<string>();
                        List<string> lstWarranty1 = new List<string>();
                        List<string> lstWarrantyDetails1 = new List<string>();
                        if (hidLocation.Value.ToString().Contains("/") && hidLocation.Value.ToString().Contains("|") && hidLocation.Value.ToString().Contains(":"))
                        {
                            string[] strMainArray = hidLocation.Value.ToString().Split('/');
                            foreach (string strSubArray in strMainArray)
                            {
                                string[] str = strSubArray.ToString().Split(',');
                                lstLocationId.Add(str[0].ToString());
                                string[] str1 = str[1].ToString().Split('|');
                                lstLocationQty.Add(str1[0].ToString());
                                string[] str2 = str1[1].ToString().Split(':');
                                lstBatchId.Add(str2[0].ToString());
                                string[] str3 = str2[1].ToString().Split(';');
                                lstWarranty1.Add(str3[0].ToString());
                                lstWarrantyDetails1.Add(str3[1].ToString());
                            }
                        }
                        else
                        {
                            string[] str = hidLocation.Value.ToString().Split(',');
                            lstLocationId.Add(str[0].ToString());
                            string[] str1 = str[1].ToString().Split('|');
                            lstLocationQty.Add(str1[0].ToString());
                            string[] str2 = str1[1].ToString().Split(':');
                            lstBatchId.Add(str2[0].ToString());
                            string[] str3 = str2[1].ToString().Split(';');
                            lstWarranty1.Add(str3[0].ToString());
                            lstWarrantyDetails1.Add(str3[1].ToString());
                        }
                        if (lstLocationId != null)
                        {
                            int Count = Convert.ToInt32(lstLocationId.Count);
                            for (int j = 0; j < Count; j++)
                            {
                                SqlParameter[] sparam ={
                                                               new SqlParameter("@TITID",tranItemId.ToString()),
                                                               new SqlParameter("@WHSID",lstLocationId[j].ToString()),
                                                               new SqlParameter("@BATID",lstBatchId[j].ToString()),
                                                               new SqlParameter("@DETQTY",lstLocationQty[j].ToString()),
                                                               new SqlParameter("@WARRANTY",lstWarranty1[j].ToString()),
                                                               new SqlParameter("@WARRANTYPERIOD",lstWarrantyDetails1[j].ToString())                                                               
                                                           };
                                int intResult = du.executeprocedure("USP_IVR_SaveTransactionItemDetails", sparam);
                                if (intResult > 0)
                                {
                                    strsql = "Select Ident_Current('IVR_TRAN_ITEMDET') as TIDID";
                                    DataTable DTTranTidid = du.getdata(strsql);
                                    if (DTTranTidid.Rows.Count > 0)
                                    {
                                        SqlParameter[] sparam1 ={
                                                               new SqlParameter("@TYOFENTRY","2"),
                                                               new SqlParameter("@ENTRYID",tranId.ToString()),
                                                               new SqlParameter("@ITMROWID",DTTranTidid.Rows[0]["TIDID"].ToString()),
                                                               new SqlParameter("@ITMID",ddlItems.SelectedValue),
                                                               new SqlParameter("@WHID",lstLocationId[j].ToString()),
                                                               new SqlParameter("@BATCHID",lstBatchId[j].ToString()),                                                               
                                                               new SqlParameter("@QTYPRIM",lstLocationQty[j].ToString()),                                                              
                                                               new SqlParameter("@RATE_PRIMUNIT",txtRate.Text.Trim()),                                                             
                                                               new SqlParameter("@ENTRYDATE",strTransDate)
                                                                };
                                        int Result = du.executeprocedure("USP_IVR_SaveStockDetails", sparam1);
                                        if (Result > 0)
                                        {
                                            intResult = 0;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else if (isBatchEnabled(ddlItems.SelectedValue) && !isWarrantyEnabled(ddlItems.SelectedValue))
                    {
                        List<string> lstLocationId = new List<string>();
                        List<string> lstBatchId = new List<string>();
                        List<string> lstLocationQty = new List<string>();
                        if (hidLocation.Value.ToString().Contains("/") && hidLocation.Value.ToString().Contains("|"))
                        {
                            string[] strMainArray = hidLocation.Value.ToString().Split('/');
                            foreach (string strSubArray in strMainArray)
                            {
                                string[] str = strSubArray.ToString().Split(',');
                                lstLocationId.Add(str[0].ToString());
                                string[] str1 = str[1].ToString().Split('|');
                                lstLocationQty.Add(str1[0].ToString());
                                lstBatchId.Add(str1[1].ToString());
                            }
                        }
                        else
                        {
                            string[] str = hidLocation.Value.ToString().Split(',');
                            lstLocationId.Add(str[0].ToString());
                            string[] str1 = str[1].ToString().Split('|');
                            lstLocationQty.Add(str1[0].ToString());
                            lstBatchId.Add(str1[1].ToString());
                        }
                        if (lstLocationId != null)
                        {
                            int Count = Convert.ToInt32(lstLocationId.Count);
                            for (int j = 0; j < Count; j++)
                            {
                                SqlParameter[] sparam ={
                                                               new SqlParameter("@TITID",tranItemId.ToString()),
                                                               new SqlParameter("@WHSID",lstLocationId[j].ToString()),
                                                               new SqlParameter("@BATID",lstBatchId[j].ToString()),
                                                               new SqlParameter("@DETQTY",lstLocationQty[j].ToString()),
                                                               new SqlParameter("@WARRANTY","0"),
                                                               new SqlParameter("@WARRANTYPERIOD","0")                                                               
                                                           };
                                int intResult = du.executeprocedure("USP_IVR_SaveTransactionItemDetails", sparam);
                                if (intResult > 0)
                                {
                                    strsql = "Select Ident_Current('IVR_TRAN_ITEMDET') as TIDID";
                                    DataTable DTTranTidid = du.getdata(strsql);
                                    if (DTTranTidid.Rows.Count > 0)
                                    {
                                        SqlParameter[] sparam1 ={
                                                               new SqlParameter("@TYOFENTRY","2"),
                                                               new SqlParameter("@ENTRYID",tranId.ToString()),
                                                               new SqlParameter("@ITMROWID",DTTranTidid.Rows[0]["TIDID"].ToString()),
                                                               new SqlParameter("@ITMID",ddlItems.SelectedValue),
                                                               new SqlParameter("@WHID",lstLocationId[j].ToString()),
                                                               new SqlParameter("@BATCHID",lstBatchId[j].ToString()),                                                               
                                                               new SqlParameter("@QTYPRIM",lstLocationQty[j].ToString()),                                                              
                                                               new SqlParameter("@RATE_PRIMUNIT",txtRate.Text.Trim()),                                                             
                                                               new SqlParameter("@ENTRYDATE",strTransDate)
                                                                };
                                        int Result = du.executeprocedure("USP_IVR_SaveStockDetails", sparam1);
                                        if (Result > 0)
                                        {
                                            intResult = 0;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else if (!isBatchEnabled(ddlItems.SelectedValue) && !isWarrantyEnabled(ddlItems.SelectedValue))
                    {
                        List<string> lstLocationId = new List<string>();
                        List<string> lstLocationQty = new List<string>();
                        if (hidLocation.Value.ToString().Contains("/"))
                        {
                            string[] strMainArray = hidLocation.Value.ToString().Split('/');
                            foreach (string strSubArray in strMainArray)
                            {
                                string[] str = strSubArray.ToString().Split(',');
                                lstLocationId.Add(str[0].ToString());
                                lstLocationQty.Add(str[1].ToString());
                            }
                        }
                        else
                        {
                            string[] str = hidLocation.Value.ToString().Split(',');
                            lstLocationId.Add(str[0].ToString());
                            lstLocationQty.Add(str[1].ToString());
                        }
                        if (lstLocationId != null)
                        {
                            int Count = Convert.ToInt32(lstLocationId.Count);
                            for (int j = 0; j < Count; j++)
                            {
                                SqlParameter[] sparam ={
                                                               new SqlParameter("@TITID",tranItemId.ToString()),
                                                               new SqlParameter("@WHSID",lstLocationId[j].ToString()),                                                               
                                                               new SqlParameter("@DETQTY",lstLocationQty[j].ToString()),
                                                               new SqlParameter("@WARRANTY","0"),
                                                               new SqlParameter("@WARRANTYPERIOD","0")                                                               
                                                           };
                                int intResult = du.executeprocedure("USP_IVR_SaveTransactionItemDetails", sparam);
                                if (intResult > 0)
                                {
                                    strsql = "Select Ident_Current('IVR_TRAN_ITEMDET') as TIDID";
                                    DataTable DTTranTidid = du.getdata(strsql);
                                    if (DTTranTidid.Rows.Count > 0)
                                    {
                                        SqlParameter[] sparam1 ={
                                                               new SqlParameter("@TYOFENTRY","2"),
                                                               new SqlParameter("@ENTRYID",tranId.ToString()),
                                                               new SqlParameter("@ITMROWID",DTTranTidid.Rows[0]["TIDID"].ToString()),
                                                               new SqlParameter("@ITMID",ddlItems.SelectedValue),
                                                               new SqlParameter("@WHID",lstLocationId[j].ToString()),
                                                               new SqlParameter("@BATCHID","0"),                                                               
                                                               new SqlParameter("@QTYPRIM",lstLocationQty[j].ToString()),                                                              
                                                               new SqlParameter("@RATE_PRIMUNIT",txtRate.Text.Trim()),                                                             
                                                               new SqlParameter("@ENTRYDATE",strTransDate)
                                                                };
                                        int Result = du.executeprocedure("USP_IVR_SaveStockDetails", sparam1);
                                        if (Result > 0)
                                        {
                                            intResult = 0;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    //
}
